<?php

namespace app\common\model;

use app\common\model\ServiceBind as ServiceBindModel;

class ServiceItem extends BaseModel
{
    protected $name = "service_item";

    /**
     * 获取数据列表
     */
    public function getList()
	{
		return $this->order('created_at', 'desc')->paginate();
	}

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $data): string
    {
        //添加时销毁自带的主键id
        unset($data['id']);
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 获取全部数据
     * @return array
     */
    public function getRows(): array
    {
        return $this->field('id,item_name,unique_no')->select()->toArray();
    }

    /**
     * 获取服务分类列表数据
     */
    public function getFwClass()
    {
        return $this->field('id,item_name,summary,image')
                ->paginate($this->pageLimit)
                ->each(function($item, $key){
                    $contain = (new ServiceBindModel)->where('item_id', $item['id'])->field('children')->find();

                    if (isset($contain) && !empty($contain))
                    {
                        $containArr = $contain->toArray();

                        $item['contain'] = count($containArr['children']).'项服务';
                    }else{
                        $item['contain'] = '0项服务';
                    }
                    return $item;
                });
    }

    /**
     * 根据id获取数据
     */
    public function getWhereId($id)
    {
        return $this->where('id', $id)->find();
    }

    /**
     * 删除数据
     * @param array $param
     */
    public function del(array $param)
    {
        return self::destroy($param['id']);
    }

}